package com.uduemc.security.browser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class MyUserDetailsService implements UserDetailsService {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 可以注入具体的服务或者 mapper
	 * 主要是查询数据库的作用
	 */
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		logger.info("获取到的用户名：" + username);
		// 根据用户名，通过数据库等查找用户信息
		
		/**
		 * 关于：org.springframework.security.core.userdetails.User
		 * 这个类是Spring提供的默认实现 UserDetails 借口
		 * 第二个参数
		 * 	密码：是从数据库中查询出来的密码串
		 * 第三个参数
		 * 	权限，是一个集合
		 *  AuthorityUtils.commaSeparatedStringToAuthorityList("admin")
		 *  将字符串转成需要的对象集合，根据逗号进行分割
		 */
		//return new User(username, "123456", AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
		
		// 是否可用
		boolean enabled = true;
		// 用户是否过期
		boolean accountNonExpired = true;
		// 密码是否过期
		boolean credentialsNonExpired = true;
		// 用户是否被锁定
		boolean accountNonLocked = true;
		// 模拟从数据库中获取密码
		String password = passwordEncoder.encode("123456");
		
		logger.info("密码："+password);
		
		return new User(
				username, 
				password, 
				enabled, 
				accountNonExpired, 
				credentialsNonExpired, 
				accountNonLocked, 
				AuthorityUtils.commaSeparatedStringToAuthorityList("admin")
				);
	}

}
